package Netty.权威指导demo.TCP粘包拆包解决;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.util.Date;

public class TimeServer {

    public void bind(int port) throws InterruptedException {
        // 配置服务端的NIO线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //设置线程队列得到连接个数
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 新增两个解码器 LineBasedFrameDecoder StringDecoder
                            /**
                             * LineBasedFrameDecoder 吃一次遍历ByteBuf中的可读字节，判断看是否有 \n或\n\r
                             * 就以此位置为结束位置，从可读索引到结束位置区间的字节就组成了一行，是以换行为结束标志的解码器，支持携带结束符或者不懈怠结束符两种解码方式
                             * 同时支持配置单行的最大长度，如果连续读取到最大长度后仍然没有发现换行符，就会抛出异常，并忽略掉之前的异常码流
                             *
                             * StringDecoder 将接收到的对象转换成字符串，然后继续调用后面的Handler
                             *
                             * LineBasedFrameDecoder + StringDecoder组合就是按行切换的文本解码器，被用来处理TCP的粘包和拆包
                             */
                            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new TimeServerHandler());
                        }
                    });
            // 绑定端口，同步等待成功
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        new TimeServer().bind(port);
    }

    class TimeServerHandler extends ChannelInboundHandlerAdapter {

        private int counter;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            //获取客户端发送过来的消息
            String body = (String) msg;
            // 打印客户端消息
//            System.out.println("服务端收到消息 : " + body);
            System.out.println("服务端收到消息 : " + body + " ; counter : " + ++counter);
            // 组装服务端发送到客户端消息
            String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()) + " " + counter : "BAD ORDER " + counter;
            currentTime = currentTime + System.getProperty("line.separator");
            ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
            // 发送消息
            ctx.write(resp);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) {
            ctx.flush();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }

}
